import isEmpty from 'loadsh/isEmpty'
import {
  GetInfoPicture,
  GetPreviewImage,
  GetTopicInfo,
  PostDeleteData,
  PostInfoPicture,
  PostTopicInfo
} from '/constData/requestFun/_httpRequest';
import {
  GetApproveLog,
  GetExportDocx,
  GetTopic,
  GetTopicById,
  GetUserInfo,
  PostTopic,
  TopicDeleteData
} from '/constData/requestFun/_teseRequest';
import compact from 'loadsh/compact'
import {
  CORPID,
  SPACEID
} from '/constData/requestFun/_globalData';
import {
  GetUserInfoFiled
} from '/constData/requestFun/_utils';
Page({
  data: {
    item: 1,
    min: null,
    max: new Date('2033/12/02'),
    defaultDate: new Date(),
    topicsinfo: {
      CorpId: '', //申请人
      ApplicatDepart: '综合部', //申请部门
      TopicTitle: '', //议题标题
      TopicContent: '', //议题论述
      ReviewConference: '支委会', //审议会议
      MeetingTime: new Date(),//会议时间
      Participants: '', //提请事项
      Annex: '[]', //附件
      Notes: '', //备注
      LawyerApproval: '', //是否需要律师审批
    },
    Select1: ['财务部', '综合部', '技术部', '研发部'],
    Select2: [{
        value: '总经理办公会',
        label: '总经理办公会'
      },
      {
        value: '支委会',
        label: '支委会'
      },
      {
        value: '董事会',
        label: '董事会'
      },
      {
        value: '股东会',
        label: '股东会'
      }
    ],
    ReceiveData: [],
    displaydata: [],
  },
  Delete(e) {
    const id = e.currentTarget.dataset.id
    TopicDeleteData(id, (res) => {
      my.alert({
        title: '撤销成功',
      });
      //刷新数据
      this.setData({
        ReceiveData: this.data.ReceiveData.filter((it) => {
          return it.item1.id !== id
        })
      })
    }, (err) => {
      my.alert({
        title: '撤销失败',
      });
    })
  },
  onLawyerApprovalChange(date) {
    this.setData({
      topicsinfo: {
        ...this.data.topicsinfo,
        LawyerApproval: date
      }
    })
  },
  onNotesChange(date) {
    this.setData({
      topicsinfo: {
        ...this.data.topicsinfo,
        Notes: date
      }
    })
  },
  onTopicTitleChange(date) {
    this.setData({
      topicsinfo: {
        ...this.data.topicsinfo,
        TopicTitle: date
      }
    })
  },
  onParticipantsChange(date) {
    this.setData({
      topicsinfo: {
        ...this.data.topicsinfo,
        Participants: date
      }
    })
  },
  handleOk(date, format, e) {
    this.setData({
      topicsinfo: {
        ...this.data.topicsinfo,
        MeetingTime: date
      },
    })
  },
  onApplicatDepartChange(e) {
    this.setData({
      topicsinfo: {
        ...this.data.topicsinfo,
        ApplicatDepart: e
      }
    })
  },
  onTopicContentChange(date) {
    this.setData({
      topicsinfo: {
        ...this.data.topicsinfo,
        TopicContent: date
      }
    })

  },
  onReviewConferenceChange(date) {
    this.setData({
      topicsinfo: {
        ...this.data.topicsinfo,
        ReviewConference: date.join(',')
      }
    })
  },
  // 选择同行人
  colleague() {
    my.complexChoose({
      title: "测试标题", //标题
      multiple: true, //是否多选
      limitTips: "超出了", //超过限定人数返回提示
      maxUsers: 1000, //最大可选人数
      pickedUsers: [], //已选用户，值为userId列表
      pickedDepartments: [], //已选的部门id
      disabledUsers: [], //不可选用户，值为userId列表
      disabledDepartments: [], //不可选部门id
      requiredUsers: [], //必选用户（不可取消选中状态）
      requiredDepartments: [], //必选部门（不可取消选中状态）
      permissionType: "xxx", //可添加权限校验，选人权限，目前只有GLOBAL这个参数
      responseUserOnly: false, //返回人，或者返回人和部门
      success: (res) => {
        // this.setData({
        //   topicsinfo: {
        //     ...this.data.topicsinfo,
        //     Participants: [],
        //   }
        // })
        // for (let index = 0; index < res.users.length; index++) {
        //   this.setData({
        //     topicsinfo: {
        //       ...this.data.topicsinfo,
        //       Participants: [...this.data.topicsinfo.Participants, res.users[index].name],
        //     }
        //   })
        // }
      },
      fail: function (err) {}
    })
  },

  //获取数据
  onLoad() {
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        new Promise((resolve) => {
          GetTopic((res) => {
            resolve(res.data);
          })
        }).then((FilterRes) => {
          // 处理 item1 的 annex  
          return Promise.all(FilterRes.map((it) => {
            it.item1['displayAnnex'] = JSON.parse(it.item1.annex);
            // 初始化 Flag 为 false  
            it.item1.Flag = false;
            return it;
          }));
        }).then((Res) => {
          // 创建一个 Promise 数组，用于获取所有 approverId 的用户信息  
          const promises = Res.map((it) => {
            const approverIds = it.item2.map(approver => approver.approverId);

            // 对每个 approverId 发起 GetUserInfo 请求  
            return Promise.all(approverIds.map(approverId => {
              return new Promise((resolve) => {
                GetUserInfo({
                  userId: approverId,
                  fileds: null
                }, (userInfo) => {
                  const name = GetUserInfoFiled(userInfo, 'name');
                  resolve({
                    approverId,
                    name
                  });
                });
              });
            })).then(userInfos => {
              // 合并用户信息到对应的 item1 中  
              const approverMap = new Map(userInfos.map(userInfo => [userInfo.approverId, userInfo.name]));
              it.item2.forEach(approver => {
                approver.approverName = approverMap.get(approver.approverId) || '未知姓名';
              });

              // 检查 item2 最后一个元素的 approvalStatus  
              const lastApprover = it.item2[it.item2.length - 1];
              if (lastApprover && !(lastApprover.approvalStatus === 1)) {
                it.item1.Flag = true;
              }
              return it;
            });
          });
          // 等待所有 Promise 完成  
          return Promise.all(promises);
        }).then((finalRes) => {
          console.log('处理后的数据', finalRes);
          this.setData({
            topicsinfo: {
              ...this.data.topicsinfo,
              CorpId: storage.data.result.userid
            },
            ReceiveData: finalRes.reverse()
          });
        }).catch((error) => {
          console.error('发生错误:', error);
        });
      }
    })
  },
  // 上传数据
  onSubmit(e) {
    console.log('提交数据', JSON.stringify(this.data.topicsinfo));
    PostTopic(JSON.stringify(this.data.topicsinfo),
      (res) => {
        my.alert({
          title: '提交成功',
        });
        my.getStorage({
          key: 'userInfo',
          success: (storage) => {
            new Promise((resolve) => {
              GetTopic((res) => {
                resolve(res.data);
              })
            }).then((FilterRes) => {
              // 处理 item1 的 annex  
              return Promise.all(FilterRes.map((it) => {
                it.item1['displayAnnex'] = JSON.parse(it.item1.annex);
                // 初始化 Flag 为 false  
                it.item1.Flag = false;
                return it;
              }));
            }).then((Res) => {
              // 创建一个 Promise 数组，用于获取所有 approverId 的用户信息  
              const promises = Res.map((it) => {
                const approverIds = it.item2.map(approver => approver.approverId);

                // 对每个 approverId 发起 GetUserInfo 请求  
                return Promise.all(approverIds.map(approverId => {
                  return new Promise((resolve) => {
                    GetUserInfo({
                      userId: approverId,
                      fileds: null
                    }, (userInfo) => {
                      const name = GetUserInfoFiled(userInfo, 'name');
                      resolve({
                        approverId,
                        name
                      });
                    });
                  });
                })).then(userInfos => {
                  // 合并用户信息到对应的 item1 中  
                  const approverMap = new Map(userInfos.map(userInfo => [userInfo.approverId, userInfo.name]));
                  it.item2.forEach(approver => {
                    approver.approverName = approverMap.get(approver.approverId) || '未知姓名';
                  });
                  // 检查 item2 最后一个元素的 approvalStatus  
                  const lastApprover = it.item2[it.item2.length - 1];
                  if (lastApprover && (lastApprover.approvalStatus === 0 || lastApprover.approvalStatus === 1)) {
                    it.item1.Flag = true;
                  }
                  return it;
                });
              });
              // 等待所有 Promise 完成  
              return Promise.all(promises);
            }).then((finalRes) => {
              this.setData({
                topicsinfo: {
                  ...this.data.topicsinfo,
                  CorpId: storage.data.result.userid
                },
                ReceiveData: finalRes.reverse()
              });
            }).catch((error) => {
              console.error('发生错误:', error);
            });
          }
        })
        this.setData({
          topicsinfo: {
            ...this.data.topicsinfo,
            ApplicatDepart: '', //申请部门
            TopicTitle: '', //议题标题
            TopicContent: '', //议题论述
            ReviewConference: '', //审议会议
            MeetingTime: '',//会议时间
            Participants: '', //提请事项
            Annex: '[]', //附件
            Notes: '', //备注
            LawyerApproval: '', //是否需要律师审批
          }
        })
      },
      (err) => {
        my.alert({
          title: '提交成功1',
        });
      })
  },
  Export(e){
    GetExportDocx(e.currentTarget.dataset.item.item1.id)
  },
  //上传图片
  onUpload() {
    let imageAnnex = ''
    dd.uploadAttachmentToDingTalk({
      image: {
        max: 9,
        spaceId: SPACEID,
        compress: true,
        folderId: '',
        multiple: true,
      },
      types: ['photo'],
      success: (res) => {
        const srcAnnex = this.data.topicsinfo.Annex
        imageAnnex = res.data
        imageAnnex.push(...JSON.parse(srcAnnex))
        this.setData({
          displaydata: imageAnnex,
          topicsinfo: {
            ...this.data.topicsinfo,
            Annex: JSON.stringify(imageAnnex)
          }
        })
      },
      fail: () => {},
      complete: () => {},
    });
  },
  PreviewBtn(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
  CheckPictures(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },

});